

var OPENSHARE = {
  consoleService : null,
  
  logMessage : function logMessage(msg) {
    if (!OPENSHARE.consoleService) {
      OPENSHARE.consoleService = Components.classes[ "@mozilla.org/consoleservice;1"].
        getService( Components.interfaces.nsIConsoleService);
    }
    OPENSHARE.consoleService.logStringMessage( "openshare: " + msg);
  },

  onError : function onError(responseText) {
    OPENSHARE.logMessage(responseText);
  },

  onReady : function onReady(responseXML) {
    OPENSHARE.logMessage(responseXML);
  },

  retrieveOpenShare : function retrieveOpenShare(doc, hrefStr) {
    try {
      var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance();
      try {
        req.open('GET', hrefStr, true);
      } catch (openException) {
        Components.utils.reportError("IcXrdsRetrieveX: failed to open " + hrefStr + "\n" + openException);
        throw openException;
      }
      req.setRequestHeader('Content-Type', 'text/xml');
      req.overrideMimeType('text/xml');
      req.onreadystatechange = function (aEvent) {
        if (req.readyState == 4) {
           if (!req.responseXML) {
              OPENSHARE.onError(req.responseText);
              return;
           }
           if (req.status != 200) {
             OPENSHARE.onError(req.statusText);
             return;
           }
           OPENSHARE.onReady(req.responseXML);
        }
      };
      req.send(null);
    } catch (e) {
      Components.utils.reportError(e);
      throw e;
    }
  },
  
  processLinkElements : function processLinkElements(doc) {
    var linkElems = doc.getElementsByTagName( "LINK");
    for( var i = 0; i < linkElems.length; i++) {
       var linkElem = linkElems[ i];
       var relStr = linkElem.getAttribute( "REL");
       if( (relStr !== null) && (relStr === "share")) {
          var hrefStr = linkElem.getAttribute( "HREF");
          if (hrefStr === null) {
             continue;
             }
          else {
             OPENSHARE.retrieveOpenShare(doc, hrefStr);
          }
       } else {
          continue;
       }
    }
  },
  
  load : function load() {
    var doc = gBrowser.selectedBrowser.contentDocument;
    if( doc.wrappedJSObject)
    {
      doc = doc.wrappedJSObject;
    }
    doc.__openshare__ = {};
    OPENSHARE.processLinkElements(doc);
  },

  unload : function unload() {
  
  },

  defaultSites : function defaultSites(event) {
    var osns = new Namespace("osns", "http://code.google.com/p/socialagent-openshare/");
    var sites = new XML("<OpenShareSites/>");
    var delicious = new XML("<OpenShareDescription xmlns=\"http://code.google.com/p/socialagent-openshare/\" " +
      "xmlns:moz=\"http://www.mozilla.org/2010/browser/share/\">" +
      "<ShortName>Delicious</ShortName>" +
      "<Description>Delicious the biggest collection of bookmarks in the universe...</Description>" +
      "<InputEncoding>UTF-8</InputEncoding>" +
      "<Image alt=\"Bookmark this on Delicious\" width=\"10\" height=\"10\" type=\"image/x-icon\">http://static.delicious.com/img/delicious.small.gif</Image>" +
      "<Url type=\"text/html\" method=\"GET\" template=\"http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=+{location}+&amp;title=+{title}\"/>" +
      "<moz:ShareForm>shareFormURL</moz:ShareForm>" +
      "</OpenShareDescription>");
    sites.appendChild(delicious);
    return sites;
},

  onUrlBarClick : function _onUrlBarClick(event) {
    var osns = new Namespace("osns", "http://code.google.com/p/socialagent-openshare/");
    
    var sitesXml = OPENSHARE.defaultSites();
    alert(sitesXml.toXMLString());
    var sites = sitesXml.osns::OpenShareDescription;
    alert(sites.toXMLString());
    var theSite;
    var theDefaultSite = "Delicious";
    for each (site in sites) {
      var shortName = site.osns::ShortName.*[0].toXMLString();
      alert(shortName);
      if (shortName == theDefaultSite) {
        alert("theDefaultSite=" + theDefaultSite );
        theSite = site;
      }
    }
    if (!theSite) {
      alert("no site to share with found");
      return;
    }
    var baseUrl = theSite.osns::Url.@template.toXMLString();
    var doc = gBrowser.selectedBrowser.contentDocument;
    var i = baseUrl.indexOf("{location}");
    if (i>0) {
      baseUrl = baseUrl.replace("{location}", escape(doc.location.href));
    }
    i = baseUrl.indexOf("{title}");
    if (i>0) {
      baseUrl = baseUrl.replace("{title}", escape(doc.title));
    }
    // FIXME ensure valid URI format and scheme == http(s) 
    window.open(baseUrl);
  }
  
};